//
//  KLSendChildKeyViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/5/23.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLSendChildKeyViewController.h"
#import "KLHttpAPI.h"
#import "KLHelp.h"
#import "InputText.h"
#import "CalenderView.h"
#import "DateViewController.h"
#import "Masonry.h"
#import "HemaFunction.h"
#import "JRToast.h"
#import "BuleFuction.h"
#import "NSData+hex.h"
#import "NSString+Hex.h"
#import "IdentifierValidator.h"
#import "KLRechargeViewController.h"
#import "BeeCloud+Utils.h"
#import "SSKeychain.h"
#import <AddressBookUI/ABPeoplePickerNavigationController.h>
#import <AddressBook/ABPerson.h>
#import <AddressBookUI/ABPersonViewController.h>

@interface KLSendChildKeyViewController ()<UITextFieldDelegate,UIAlertViewDelegate,UIActionSheetDelegate,BeeCloudDelegate,UITableViewDelegate,UITableViewDataSource,ABPeoplePickerNavigationControllerDelegate>
{
    UIView *datePopView_start;
    UIDatePicker *datePickerYMD_start;
    UIDatePicker *datePickerHM_start;
    UIButton *dateConfirmBtn_start;
    
    NSString *YMD_start;
    NSString *HM_start;
    
    UIView *datePopView_end;
    UIDatePicker *datePickerYMD_end;
    UIDatePicker *datePickerHM_end;
    UIButton *dateConfirmBtn_end;
    
    NSString *YMD_end;
    NSString *HM_end;
    NSDateFormatter *YMDft;
    NSDateFormatter *HMft;
    NSDateFormatter *YMD_HM_ft;
}

@property (nonatomic, strong)UITextField *mobielText;
@property (nonatomic, strong)UILabel *mobielTextLabel;
@property (nonatomic, assign) BOOL chang;

@property (nonatomic, strong)UIButton *pickStartTime;
@property (nonatomic, strong)UIButton *pickEndTime;

@property (nonatomic, strong)NSString *sTimeToLock;
@property (nonatomic, strong)NSString *eTimeToLock;
@property (nonatomic, strong)NSString *sTimeToServe;
@property (nonatomic, strong)NSString *eTimeToServe;

@property (nonatomic, strong)NSString *totalFee;
@property (nonatomic, strong)NSString *key_str;
@property (nonatomic, strong)NSString *trade_no;
@property (nonatomic, strong)NSString *money;

@property (nonatomic, strong)UIImageView *addressList;
@property (nonatomic,strong)UITableView *recentlyPhoneTableView;
@property (nonatomic,strong)NSArray *phoneListArr;
@end

@implementation KLSendChildKeyViewController

-(UITableView *)recentlyPhoneTableView{
    if(!_recentlyPhoneTableView){
        _recentlyPhoneTableView = [[UITableView alloc]init];
        _recentlyPhoneTableView.delegate = self;
        _recentlyPhoneTableView.dataSource = self;
        _recentlyPhoneTableView.rowHeight = 30.0f;
        _recentlyPhoneTableView.tableFooterView = [[UIView alloc]init];
        _recentlyPhoneTableView.layer.masksToBounds = YES;
        _recentlyPhoneTableView.layer.cornerRadius = 7;
        _recentlyPhoneTableView.backgroundColor = RGB_UI_COLOR(242, 230, 230);
    }
    return _recentlyPhoneTableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化导航栏
    [self naveSet];
    //初始化界面设置
    [self uiSet];
    YMDft = [[NSDateFormatter alloc]init];
    [YMDft setDateFormat:@"yyyy-MM-dd"];
    HMft = [[NSDateFormatter alloc]init];
    [HMft setDateFormat:@"HH:mm"];
    YMD_HM_ft = [[NSDateFormatter alloc]init];
    [YMD_HM_ft setDateFormat:@"yyyy-MM-dd HH:mm"];
}

#pragma mark - 界面设置
//初始化导航栏
-(void)naveSet{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = NO;
    if([self.keyType isEqualToString:@"1"]){
        self.title = @"分发平等钥匙";
    }else {
        self.title = @"分发临时钥匙";
    }
    
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

//初始化主界面
- (void)uiSet{
    //输入手机号的textfield和label
    CGFloat centerX = UI_View_Width * 2 / 5 + 15;
    InputText *inputText = [[InputText alloc] init];
    CGFloat userY = 50;
    UITextField *mobielText = [inputText setupWithIcon:nil textY:userY centerX:centerX point:nil];
    mobielText.keyboardType = UIKeyboardTypeNumberPad;
    [mobielText setReturnKeyType:UIReturnKeyNext];
    mobielText.delegate = self;
    self.mobielText = mobielText;
    [mobielText setReturnKeyType:UIReturnKeyNext];
    [self.view addSubview:mobielText];
    UILabel *mobielTextLabel = [self setupTextName:@"请输入对方手机号" frame:mobielText.frame];
    self.mobielTextLabel = mobielTextLabel;
    [self.view addSubview:mobielTextLabel];
    
    self.addressList = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"通讯录"]];
    self.addressList.userInteractionEnabled = YES;
    self.addressList.layer.masksToBounds = YES;
    self.addressList.layer.cornerRadius = 4;
    [self.view addSubview:self.addressList];
    [self.addressList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(25);
        make.height.mas_equalTo(25);
        make.right.equalTo(self.mobielText).with.offset(35);
        make.centerY.equalTo(self.mobielText);
    }];
    UITapGestureRecognizer *tapAddressList = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAddressList:)];
    [self.addressList addGestureRecognizer:tapAddressList];
    
    //选择起始时间按钮
    self.pickStartTime = [[UIButton alloc]init];
    if([self.keyType isEqualToString:@"2"]){
        [self.pickStartTime setTitle:@"选择临时钥匙有效期的起始时间" forState:UIControlStateNormal];
    }else{
        [self.pickStartTime setTitle:@"选择平等钥匙有效期的起始时间" forState:UIControlStateNormal];
    }
    [self.pickStartTime setTitleColor:RGB_UI_COLOR(51, 153, 255) forState:UIControlStateNormal];
    [self.pickStartTime.layer setMasksToBounds:YES];
    [self.pickStartTime.layer setCornerRadius:5.0f];
    [self.pickStartTime.layer setBorderWidth:1.0f];
    [self.pickStartTime.layer setBorderColor:[RGB_UI_COLOR(51, 153, 255) CGColor]];
    
    [self.pickStartTime addTarget:self action:@selector(datePickerStart:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.pickStartTime];
    [self.pickStartTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(mobielTextLabel.mas_bottom).with.offset(30);
        make.centerX.equalTo(self.view).offset(0);
        make.width.mas_equalTo(UI_View_Width-40);
        make.height.mas_equalTo(40);
    }];
    
    //选择结束时间按钮
    self.pickEndTime = [[UIButton alloc]init];
    if([self.keyType isEqualToString:@"2"]){
        [self.pickEndTime setTitle:@"选择临时钥匙有效期的结束时间" forState:UIControlStateNormal];
    }else{
        [self.pickEndTime setTitle:@"选择平等钥匙有效期的结束时间" forState:UIControlStateNormal];
    }
    [self.pickEndTime setTitleColor:RGB_UI_COLOR(51, 153, 255) forState:UIControlStateNormal];
    [self.pickEndTime.layer setMasksToBounds:YES];
    [self.pickEndTime.layer setCornerRadius:5.0f];
    [self.pickEndTime.layer setBorderWidth:1.0f];
    [self.pickEndTime.layer setBorderColor:[RGB_UI_COLOR(51, 153, 255) CGColor]];
    
    [self.pickEndTime addTarget:self action:@selector(datePickerEnd:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.pickEndTime];
    [self.pickEndTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pickStartTime.mas_bottom).with.offset(20);
        make.centerX.equalTo(self.view).offset(0);
        make.width.mas_equalTo(UI_View_Width-40);
        make.height.mas_equalTo(40);
    }];
    
    //提交分发按钮
    UIButton *sendBtn = [[UIButton alloc]init];
    [sendBtn setTitle:@"发 送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    sendBtn.layer.masksToBounds = YES;
    sendBtn.layer.cornerRadius = 5.0f;
    sendBtn.backgroundColor = RGB_UI_COLOR(0, 255, 153);
    
    [sendBtn addTarget:self action:@selector(makeSureSend:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn];
    [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pickEndTime).with.offset(100);
        make.centerX.equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(120);
        make.height.mas_equalTo(45);
    }];
    
    //封装起始日期选择器的父view
    datePopView_start = [[UIView alloc]init];
    datePopView_start.backgroundColor = RGB_UI_COLOR(102, 153, 255);
    datePopView_start.layer.masksToBounds = YES;
    datePopView_start.layer.cornerRadius = 8.0f;
    datePopView_start.alpha = 0;
    [self.view addSubview:datePopView_start];
    [datePopView_start mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(UI_View_Width-40);
        make.height.mas_equalTo(UI_View_Height-90);
    }];
    
    //封装结束日期选择器的父view
    datePopView_end = [[UIView alloc]init];
    datePopView_end.backgroundColor = RGB_UI_COLOR(102, 153, 255);
    datePopView_end.layer.masksToBounds = YES;
    datePopView_end.layer.cornerRadius = 8.0f;
    datePopView_end.alpha = 0;
    [self.view addSubview:datePopView_end];
    [datePopView_end mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(UI_View_Width-40);
        make.height.mas_equalTo(UI_View_Height-90);
    }];
}

#pragma mark - 起始日期选择按钮点击事件
-(void)datePickerStart:(UIButton *)sender{
    [self.view endEditing:YES];
    [self.recentlyPhoneTableView removeFromSuperview];
    
    //创建年月日的时间选择器
    datePickerYMD_start = [[UIDatePicker alloc]init];
    [datePickerYMD_start addTarget:self action:@selector(YMD_start_change:) forControlEvents:UIControlEventValueChanged];
    datePickerYMD_start.minimumDate = [NSDate date];
    if(YMD_end != nil){
        datePickerYMD_start.maximumDate = [YMDft dateFromString:YMD_end];
    }
    datePickerYMD_start.datePickerMode = UIDatePickerModeDate;
    
    [datePopView_start addSubview:datePickerYMD_start];
    [datePickerYMD_start mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(datePopView_start).with.offset(0);
        make.centerY.equalTo(datePopView_start).with.offset(-datePopView_start.frame.size.height/4+50);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    //创建时分的时间选择器
    datePickerHM_start = [[UIDatePicker alloc]init];
    datePickerHM_start.minimumDate = [NSDate date];
    if(HM_end != nil){
        datePickerHM_start.maximumDate = [YMD_HM_ft dateFromString:[NSString stringWithFormat:@"%@ %@",
                                                             [YMDft stringFromDate:[NSDate date]],HM_end]];
    }
    datePickerHM_start.datePickerMode = UIDatePickerModeTime;
    [datePopView_start addSubview:datePickerHM_start];
    [datePickerHM_start mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(datePopView_start).with.offset(0);
        make.centerY.equalTo(datePopView_start).with.offset(datePopView_start.frame.size.height/4);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    
    //创建确定按钮
    dateConfirmBtn_start = [[UIButton alloc]init];
    [dateConfirmBtn_start setTitle:@"确定" forState:UIControlStateNormal];
    [dateConfirmBtn_start setTitleColor:RGB_UI_COLOR(241, 194, 50) forState:UIControlStateNormal];
    dateConfirmBtn_start.layer.masksToBounds = YES;
    dateConfirmBtn_start.layer.cornerRadius = 5.0f;
    dateConfirmBtn_start.layer.borderColor = RGB_UI_COLOR(241, 194, 50).CGColor;
    [dateConfirmBtn_start.layer setBorderWidth:1.5f];
    [dateConfirmBtn_start addTarget:self action:@selector(dateConfirmStart:) forControlEvents:UIControlEventTouchUpInside];
    [datePopView_start addSubview:dateConfirmBtn_start];
    [dateConfirmBtn_start mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(50);
        make.top.mas_equalTo(15);
    }];
    
    [UIView animateWithDuration:0.2f animations:^{
        datePopView_start.alpha = 1;
    }];
}
#pragma mark - 结束日期选择按钮点击事件
-(void)datePickerEnd:(UIButton *)sender{
    [self.view endEditing:YES];
    [self.recentlyPhoneTableView removeFromSuperview];
    
    //创建年月日的时间选择器
    datePickerYMD_end = [[UIDatePicker alloc]init];
    [datePickerYMD_end addTarget:self action:@selector(YMD_end_change:) forControlEvents:UIControlEventValueChanged];
    if(YMD_start == nil){
        datePickerYMD_end.minimumDate = [NSDate date];
    }else{
        datePickerYMD_end.minimumDate = [YMDft dateFromString:YMD_start];
    }
    datePickerYMD_end.datePickerMode = UIDatePickerModeDate;
    
    [datePopView_end addSubview:datePickerYMD_end];
    [datePickerYMD_end mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(datePopView_end).with.offset(0);
        make.centerY.equalTo(datePopView_end).with.offset(-datePopView_end.frame.size.height/4+50);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    //创建时分的时间选择器
    datePickerHM_end = [[UIDatePicker alloc]init];
    if(HM_start == nil){
        datePickerHM_end.minimumDate = [NSDate date];
    }else{
        datePickerHM_end.minimumDate = [YMD_HM_ft dateFromString:[NSString stringWithFormat:@"%@ %@",[YMDft stringFromDate:[NSDate date]],HM_start]];
    }
    datePickerHM_end.datePickerMode = UIDatePickerModeTime;
    [datePopView_end addSubview:datePickerHM_end];
    [datePickerHM_end mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(datePopView_end).with.offset(0);
        make.centerY.equalTo(datePopView_end).with.offset(datePopView_end.frame.size.height/4);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    
    //创建确定按钮
    dateConfirmBtn_end = [[UIButton alloc]init];
    [dateConfirmBtn_end setTitle:@"确定" forState:UIControlStateNormal];
    [dateConfirmBtn_end setTitleColor:RGB_UI_COLOR(241, 194, 50) forState:UIControlStateNormal];
    dateConfirmBtn_end.layer.masksToBounds = YES;
    dateConfirmBtn_end.layer.cornerRadius = 5.0f;
    dateConfirmBtn_end.layer.borderColor = RGB_UI_COLOR(241, 194, 50).CGColor;
    [dateConfirmBtn_end.layer setBorderWidth:1.5f];
    [dateConfirmBtn_end addTarget:self action:@selector(dateConfirmEnd:) forControlEvents:UIControlEventTouchUpInside];
    [datePopView_end addSubview:dateConfirmBtn_end];
    [dateConfirmBtn_end mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(50);
        make.top.mas_equalTo(15);
    }];
    
    [UIView animateWithDuration:0.2f animations:^{
        datePopView_end.alpha = 1;
    }];
    
    return;
}

#pragma mark - 起始时间选择器的确定按钮事件
-(void)dateConfirmStart:(UIButton *)sender{
    [datePickerYMD_start removeFromSuperview];
    [datePickerHM_start removeFromSuperview];
    [dateConfirmBtn_start removeFromSuperview];
    [UIView animateWithDuration:0.2f animations:^{
        datePopView_start.alpha = 0;
    }];
    
    YMD_start = [YMDft stringFromDate:datePickerYMD_start.date];
    HM_start = [HMft stringFromDate:datePickerHM_start.date];
    
    //给服务器的起始时间
    self.sTimeToServe = [NSString stringWithFormat:@"%@ %@:00",YMD_start,HM_start];
    //给锁的起始时间
    NSArray *YMD_startArr = [[YMD_start substringFromIndex:2] componentsSeparatedByString:@"-"];
    NSArray *HM_startArr = [HM_start componentsSeparatedByString:@":"];
    self.sTimeToLock = [NSString stringWithFormat:@"%@%@%@%@%@00",YMD_startArr[0],YMD_startArr[1],YMD_startArr[2],HM_startArr[0],HM_startArr[1]];
    
    //显示在按钮上的时间
    [self.pickStartTime setTitle:[NSString stringWithFormat:@"起始时间:%@ %@",YMD_start,HM_start] forState:UIControlStateNormal];
}

#pragma mark - 结束时间选择器的确定按钮事件
-(void)dateConfirmEnd:(UIButton *)sender{
    [datePickerYMD_end removeFromSuperview];
    [datePickerHM_end removeFromSuperview];
    [dateConfirmBtn_end removeFromSuperview];
    [UIView animateWithDuration:0.2f animations:^{
        datePopView_end.alpha = 0;
    }];
    
    YMD_end = [YMDft stringFromDate:datePickerYMD_end.date];
    HM_end = [HMft stringFromDate:datePickerHM_end.date];
    
    //给服务器的结束时间
    self.eTimeToServe = [NSString stringWithFormat:@"%@ %@:00",YMD_end,HM_end];
    //给锁的结束时间
    NSArray *YMD_endArr = [[YMD_end substringFromIndex:2] componentsSeparatedByString:@"-"];
    NSArray *HM_endArr = [HM_end componentsSeparatedByString:@":"];
    self.eTimeToLock = [NSString stringWithFormat:@"%@%@%@%@%@00",YMD_endArr[0],YMD_endArr[1],YMD_endArr[2],HM_endArr[0],HM_endArr[1]];
    
    //显示在按钮上的时间
    [self.pickEndTime setTitle:[NSString stringWithFormat:@"结束时间:%@ %@",YMD_end,HM_end] forState:UIControlStateNormal];
}

//起始年月日变化响应
-(void)YMD_start_change:(UIDatePicker *)sender{
    NSLog(@"起始的年月日变化了");
    NSString *starYMDstr = [YMDft stringFromDate:sender.date];
    NSString *currentYMDstr = [YMDft stringFromDate:[NSDate date]];
    if(YMD_end == nil){
        if([starYMDstr isEqualToString:currentYMDstr]){
            datePickerHM_start.minimumDate = [NSDate date];
            datePickerHM_start.maximumDate = nil;
        }else{
            datePickerHM_start.minimumDate = nil;
            datePickerHM_start.maximumDate = nil;
        }
    }else{
        if([starYMDstr isEqualToString:currentYMDstr] && ![starYMDstr isEqualToString:YMD_end]){
            datePickerHM_start.minimumDate = [NSDate date];
            datePickerHM_start.maximumDate = nil;
        }else if([starYMDstr isEqualToString:YMD_end] && ![starYMDstr isEqualToString:currentYMDstr]){
            datePickerHM_start.minimumDate = nil;
            datePickerHM_start.maximumDate = [YMD_HM_ft dateFromString:[NSString stringWithFormat:@"%@ %@",
                                                                 [YMDft stringFromDate:[NSDate date]],HM_end]];
        }else if([starYMDstr isEqualToString:YMD_end] && [starYMDstr isEqualToString:currentYMDstr]){
            datePickerHM_start.minimumDate = [NSDate date];
            datePickerHM_start.maximumDate = [YMD_HM_ft dateFromString:[NSString stringWithFormat:@"%@ %@",
                                                                        [YMDft stringFromDate:[NSDate date]],HM_end]];;
        }else{
            datePickerHM_start.minimumDate = nil;
            datePickerHM_start.maximumDate = nil;
        }
    }
}

//结束年月日变化响应
-(void)YMD_end_change:(UIDatePicker *)sender{
    NSString *endYMDstr = [YMDft stringFromDate:sender.date];
    
    if(YMD_start == nil){
        NSString *currentYMDstr = [YMDft stringFromDate:[NSDate date]];
        if([endYMDstr isEqualToString:currentYMDstr]){
            datePickerHM_end.minimumDate = [NSDate date];
        }else{
            datePickerHM_end.minimumDate = nil;
        }
    }else{
        if([endYMDstr isEqualToString:YMD_start]){
            datePickerHM_end.minimumDate = [YMD_HM_ft dateFromString:[NSString stringWithFormat:@"%@ %@",
                                                                 [YMDft stringFromDate:[NSDate date]],HM_start]];
        }else{
            datePickerHM_end.minimumDate = nil;
        }
    }
}

#pragma mark - 点击发送子钥匙
-(void)makeSureSend:(id)sender{
    if(![IdentifierValidator isValid:IdentifierTypePhone value:self.mobielText.text]){
        [JRToast showWithText:@"手机号格式有误!"];
        return;
    }
    if(self.sTimeToServe.length == 0 || self.eTimeToServe.length == 0){
        [JRToast showWithText:@"请选择钥匙有效期"];
        return ;
    }
    [KLHelp showHUDAddedTo:self.view animated:YES];
    if(self.isGroup == YES){
        //获取钥匙串价格
//        [KLHttpAPI requestGetChild_KeyPriceWithKeyType:self.keyType token:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] startDate:self.sTimeToServe endDate:self.eTimeToServe completionHandler:^(MKNetworkOperation *operation) {
//            [KLHelp hideAllHUDsForView:self.view animated:YES];
//            NSLog(@"获取的价格:%@",operation.responseString);
//            NSDictionary *dic = operation.responseJSON;
//            NSString *isSuccess = [dic objectForKey:@"success"];
//            NSString *totalfe = [dic objectForKey:@"infor"];
//            self.totalFee = [NSString stringWithFormat:@"%.2f",totalfe.doubleValue * self.keysGroupArray.count];
//            if(isSuccess.integerValue == 1){
//                UIAlertView *alert_child = [[UIAlertView alloc]initWithTitle:@"价格" message:[NSString stringWithFormat:@"此次操作支付:¥ %@元",self.totalFee] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//                alert_child.tag = 1;
//                [alert_child show];
//            }else{
//                [JRToast showWithText:[dic objectForKey:@"msg"]];
//            }
//        } errorHandler:^(NSString *error) {
//        }];
    }else{
        //获取单把价格
        [KLHttpAPI requestGetChild_KeyPriceWithStartDate:self.sTimeToServe endDate:self.eTimeToServe completionHandler:^(MKNetworkOperation *operation) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            NSLog(@"获取的价格:%@",operation.responseString);
            NSDictionary *dic = operation.responseJSON;
            NSString *isSuccess = [dic objectForKey:@"success"];
            self.totalFee = [dic objectForKey:@"infor"];
            if(isSuccess.integerValue == 1){
                UIAlertView *alert_child = [[UIAlertView alloc]initWithTitle:@"价格" message:[NSString stringWithFormat:@"此次操作支付:¥ %@元",self.totalFee] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                alert_child.tag = 2;
                [alert_child show];
            }else{
                [JRToast showWithText:[dic objectForKey:@"msg"]];
            }
        } errorHandler:^(NSString *error) {
        }];
    }
}

//发送钥匙串
-(void)sendKeyGroup{
    NSMutableArray *keystring_infor = [NSMutableArray array];
    for (NSDictionary *lockDic in self.keysGroupArray) {
        NSMutableDictionary *inforDic = [NSMutableDictionary dictionary];
        [inforDic setObject:[lockDic objectForKey:@"id"] forKey:@"lock_id"];
        [inforDic setObject:self.mobielText.text forKey:@"mobile"];
        [inforDic setObject:@"2" forKey:@"type"];
        [inforDic setObject:self.sTimeToServe forKey:@"startdate"];
        [inforDic setObject:self.eTimeToServe forKey:@"enddate"];
        [inforDic setObject:@"1" forKey:@"days"];
        [inforDic setObject:self.totalFee forKey:@"totalfee"];
        NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
        NSDictionary *publicKeysDic = [KLHelp dictionaryWithJsonString:jsonStr];
        NSString *codeStr = [publicKeysDic objectForKey:[lockDic objectForKey:@"uname"]];
        if(codeStr.length == 0){
            [KLHelp showTextHUDforView:self.view text:@"公钥丢失，请重新扫描二维码！"];
            return ;
        }
//        NSData *packageChildKey = [BuleFuction packChildkeyToData:codeStr mobileStr:self.mobielText.text startTime:self.sTimeToLock endTime:self.eTimeToLock commondCode:[lockDic objectForKey:@"serinumber"]];
//        [inforDic setObject:[packageChildKey convertDataToHexStr:packageChildKey] forKey:@"key_str"];
//        [keystring_infor addObject:inforDic];
    }
    
    //本机当前时间(用于自定义单号)
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    NSString *trade_no = [NSString stringWithFormat:@"%@%@%@",locationString,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"],self.totalFee];
    
    [KLHelp showHUDAddedTo:self.view title:@"正在分发钥匙..." details:nil animated:YES];
    [KLHttpAPI sendKeysGroupWithLockArray:keystring_infor keytype:@"2" trade_no:trade_no totalfee:self.totalFee completionHandler:^(MKNetworkOperation *operation) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSString *success = [[operation responseJSON] objectForKey:@"success"];
        if(success.integerValue == 1){
            [KLHelp showTextHUDforView:self.view text:@"钥匙已分发"];
        }else{
            [KLHelp showTextHUDforView:self.view text:[[operation responseJSON] objectForKey:@"msg"]];
        }
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [JRToast showWithText:@"发送错误"];
    }];
}

//发送单把钥匙
-(void)sendSingleKey{
    NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
    NSDictionary *publicKeysDic = [KLHelp dictionaryWithJsonString:jsonStr];
    NSString *codeStr = [publicKeysDic objectForKey:[self.currentLockDic objectForKey:@"uname"]];
    if(codeStr.length == 0){
        [KLHelp showTextHUDforView:self.view text:@"公钥丢失，请重新扫描二维码！"];
        return ;
    }
    NSData *packageChildKey;
    if([self.keyType isEqualToString:@"1"]){//发送平等钥匙
//        packageChildKey = [BuleFuction packChildkeyToData:codeStr mobileStr:self.mobielText.text startTime:self.sTimeToLock endTime:self.eTimeToLock commondCode:@"0"];
    }else{//发送临时钥匙
//        packageChildKey = [BuleFuction packChildkeyToData:codeStr mobileStr:self.mobielText.text startTime:self.sTimeToLock endTime:self.eTimeToLock commondCode:[self.currentLockDic objectForKey:@"serinumber"]];
        NSLog(@"%@ ,%@",self.sTimeToLock,self.eTimeToLock);
    }
    
    self.key_str = [packageChildKey convertDataToHexStr:packageChildKey];
    NSLog(@"打包子钥匙后的数据包的字符串:%@",self.key_str);
    
    [KLHelp showTextHUDforView:self.view text:@"正在分发钥匙..." dismissedOperate:nil];
//    [KLHttpAPI distributeChild_keyWithLockID:[self.currentLockDic objectForKey:@"id"] mobile:self.mobielText.text startdate:self.sTimeToServe enddate:self.eTimeToServe totalfee:self.totalFee rsa_data:self.key_str style:<#(NSString *)#> from_key_id:<#(NSString *)#> AESkey:[KLHelp getUserSixTeenRandomAESKey] power:<#(NSString *)#> updatetime:<#(NSString *)#> token:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] completionHandler:^(MKNetworkOperation *operation) {
//        
//    } errorHandler:^(NSString *error) {
//        
//    }];
//    [KLHttpAPI distributeChild_keyWithLockID:[self.currentLockDic objectForKey:@"id"] mobile:self.mobielText.text type:self.keyType startdate:self.sTimeToServe enddate:self.eTimeToServe days:@"1" totalfee:self.totalFee key_str:self.key_str token:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] completionHandler:^(MKNetworkOperation *operation) {
//        NSDictionary *result = [operation responseJSON];
//        NSString *isSuccess = [result objectForKey:@"success"];
//        [KLHelp hideAllHUDsForView:self.view animated:YES];
//        if(isSuccess.integerValue == 1){
//            [KLHelp showTextHUDforView:self.view text:@"钥匙已分发"];
//        }else{
//            [KLHelp showTextHUDforView:self.view text:[[operation responseJSON] objectForKey:@"msg"]];
//        }
//    } errorHandler:^(NSString *error) {
//        [KLHelp hideAllHUDsForView:self.view animated:YES];
//    }];
}

#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 0){
        return ;
    }
    NSString *amount = [[NSUserDefaults standardUserDefaults] objectForKey:@"feeaccount"];
    if(amount.doubleValue < self.totalFee.doubleValue){
        UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"当前余额不足" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"充值",@"在线支付", nil];
        [sheet showInView:self.view];

        return ;
    }
    if(alertView.tag == 2 && buttonIndex == 1){
        [self sendSingleKey];
    }else if(alertView.tag == 1 && buttonIndex == 1){
        [self sendKeyGroup];
    }
}

#pragma mark - UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%zd",buttonIndex);
    if(buttonIndex == 0){//充值
        KLRechargeViewController *rechargeVC = [[KLRechargeViewController alloc]init];
        [self.navigationController pushViewController:rechargeVC animated:YES];
    }else if(buttonIndex == 1){//在线支付
        //设置支付代理
        self.money = [NSString stringWithFormat:@"%.f",self.totalFee.doubleValue * 100];
        [BeeCloud setBeeCloudDelegate:self];
        //充值
        [self recharge];
    }
}

-(void)recharge{
    //本机当前时间(用于自定义单号)
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    
    //支付请求
    [BeeCloud initWithAppID:@"1e70e317-1286-490b-ad3b-3d56f8f2e0a0" andAppSecret:@"caf7da3a-1b60-499c-920c-5d0c2008693a"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.money,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"], nil];
    /**
     按住键盘上的option键，点击参数名称，可以查看参数说明
     **/
    BCPayReq *payReq = [[BCPayReq alloc] init];
    payReq.channel = PayChannelAliApp; //支付渠道
    payReq.title = @"KISSLOCK蓝牙锁在线支付";//订单标题
    payReq.totalFee = [NSString stringWithFormat:@"%@",self.money];//订单价格
    self.trade_no = [NSString stringWithFormat:@"0002%@%@",locationString,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]];
    payReq.billNo = self.trade_no;//商户自定义订单号
    payReq.scheme = @"prefsGuoYangKissLock";//URL Scheme,在Info.plist中配置; 支付宝必有参数
    payReq.billTimeOut = 300;//订单超时时间
    payReq.viewController = self; //银联支付和Sandbox环境必填
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}

#pragma mark - BCPay回调
- (void)onBeeCloudResp:(BCBaseResp *)resp {
    if(resp.type == BCObjsTypePayResp){
        // 支付请求响应
        BCPayResp *tempResp = (BCPayResp *)resp;
        if (tempResp.resultCode == 0) {
            NSLog(@"支付情况：%@",resp.resultMsg);
            [KLHttpAPI payoffSuccessWithKeytype:@"1" total_fee:self.money trade_no:self.trade_no completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"充值返回数据：%@",operation.responseString);
                NSDictionary *dic = operation.responseJSON;
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:@"msg"] forKey:@"feeaccount"];
                    if(self.isGroup){
                        [self sendKeyGroup];
                    }else{
                        [self sendSingleKey];
                    }
                }else{
                    [KLHelp showTextHUDforView:self.view text:@"充值失败"];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:@"充值失败"];
            }];
            
        } else {
            //支付取消或者支付失败
            NSLog(@"支付取消或失败结果信息:resultMsg：%@, errDetail：%@, type：%zd, resultCode：%zd",tempResp.resultMsg,tempResp.errDetail,tempResp.request.type,tempResp.resultCode);
        }
    }
}

#pragma mark - UITextField的代理
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [self diminishTextName:self.mobielTextLabel];
    [self getHistoryPhoneList];
    
    return YES;
}

- (void)diminishTextName:(UILabel *)label{
    [UIView animateWithDuration:0.5 animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, -16);
        label.font = [UIFont systemFontOfSize:9];
    }];
}

- (void)restoreTextName:(UILabel *)label textField:(UITextField *)textFieled{
    [self textFieldTextChange:textFieled];
    if (self.chang) {
        [UIView animateWithDuration:0.5 animations:^{
            label.transform = CGAffineTransformIdentity;
            label.font = [UIFont systemFontOfSize:16];
        }];
    }
}

- (void)textFieldTextChange:(UITextField *)textField{
    if (textField.text.length != 0) {
        self.chang = NO;
    } else {
        self.chang = YES;
    }
}

- (UILabel *)setupTextName:(NSString *)textName frame:(CGRect)frame{
    UILabel *textNameLabel = [[UILabel alloc] init];
    textNameLabel.text = textName;
    textNameLabel.font = [UIFont systemFontOfSize:16];
    textNameLabel.textColor = [UIColor grayColor];
    textNameLabel.frame = frame;
    return textNameLabel;
}

#pragma mark - touchesBegan
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    [self restoreTextName:self.mobielTextLabel textField:self.mobielText];
    [self.recentlyPhoneTableView removeFromSuperview];
}

#pragma mark - 最近联系人列表
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.phoneListArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"phoneList"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"phoneList"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.textLabel.text = [self.phoneListArr[indexPath.row] objectForKey:@"mobile"];
    cell.detailTextLabel.text = [self.phoneListArr[indexPath.row] objectForKey:@"name"];
    cell.backgroundColor = [UIColor clearColor];
    
    if(indexPath.row == self.phoneListArr.count-1){
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, cell.bounds.size.width-100);
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.mobielText.text = [self.phoneListArr[indexPath.row] objectForKey:@"mobile"];
    [self.view endEditing:YES];
    [self.recentlyPhoneTableView removeFromSuperview];
}

#pragma mark - 获取历史手机记录
-(void)getHistoryPhoneList{
    [KLHttpAPI requestHistorySendKeysPhoneListWithClientID:[[NSUserDefaults standardUserDefaults] objectForKey:@"userid"] completionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"历史手机号记录:%@",operation.responseJSON);
        NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            self.phoneListArr = [NSArray arrayWithArray:[operation.responseJSON objectForKey:@"infor"]];
            [self.view addSubview:self.recentlyPhoneTableView];
            [self.recentlyPhoneTableView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(self.mobielText.frame.size.width);
                if(self.phoneListArr.count > 4){
                    make.height.mas_equalTo(130);
                    make.updateExisting = YES;
                }else{
                    make.height.mas_equalTo(self.phoneListArr.count*30+3);
                    make.updateExisting = YES;
                }
                make.top.equalTo(self.mobielText).with.offset(25);
                make.centerX.equalTo(self.mobielText);
            }];
            [self.recentlyPhoneTableView reloadData];
        }
    } errorHandler:^(NSString *error) {
    }];
}

#pragma mark - 选择通讯录
-(void)tapAddressList:(UITapGestureRecognizer *)tap{
    [KLHelp showHUDAddedTo:self.view animated:YES];
    ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];
    nav.peoplePickerDelegate = self;
    
    //这个变量用于记录授权是否成功，即用户是否允许我们访问通讯录
    int __block tip=0;
    //声明一个通讯簿的引用
    ABAddressBookRef addBook =nil;
    //因为在IOS6.0之后和之前的权限申请方式有所差别，这里做个判断
    if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
        //创建通讯簿的引用
        addBook=ABAddressBookCreateWithOptions(NULL, NULL);
        //创建一个出事信号量为0的信号
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        //申请访问权限
        ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef error)        {
            //greanted为YES是表示用户允许，否则为不允许
            if (!greanted) {
                tip=1;
            }else{
                if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0){
                    nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
                }
                [self presentViewController:nav animated:YES completion:nil];
                [KLHelp hideAllHUDsForView:self.view animated:YES];
            }
            //发送一次信号
            dispatch_semaphore_signal(sema);
        });
        //等待信号触发
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }else{
        //IOS6之前
        addBook =ABAddressBookCreate();
    }
    
}

//取消选择
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }
    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    [self diminishTextName:self.mobielTextLabel];
    self.mobielText.text = phoneNO;
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
    personViewController.displayedPerson = person;
    [peoplePicker pushViewController:personViewController animated:YES];
}
@end
